package com.truthbean.jeetb.utils.web.invoker;

import com.truthbean.jeetb.utils.web.Utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;

public class DownInvoker extends DefaultInvoker {
    public boolean doBefore() {
        return false;
    }

    public boolean doAfter() {
        return false;
    }

    public void invoke(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {
        try {
            String path = request.getParameter("path");
            if (Utils.isEmpty(path))
                return;
            File f = new File(path);
            if (!f.exists())
                return;
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(f.getName(), PAGE_CHARSET));
            BufferedInputStream input = new BufferedInputStream(new FileInputStream(f));
            BufferedOutputStream output = new BufferedOutputStream(response.getOutputStream());
            byte[] data = new byte[1024];
            int len = input.read(data);
            while (len != -1) {
                output.write(data, 0, len);
                len = input.read(data);
            }
            input.close();
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
}